﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Top.Api.Domain;
using Top.Api.Request;
using Top.Api.Response;
using Top.Api;
using DBControl;
using System.Data;
using System.Data.SqlClient;

namespace KSGJ
{
    public partial class allindex : validationclass
    {
        private static string appkey = System.Configuration.ConfigurationManager.AppSettings["AppKey"].ToString();
        private static string appsecret = System.Configuration.ConfigurationManager.AppSettings["AppSecret"].ToString();
        private static string appurl = System.Configuration.ConfigurationManager.AppSettings["AppUrl"].ToString();
        private static ITopClient client = new DefaultTopClient(appurl, appkey, appsecret);

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //判断是否是子账户登录
                //if (Session["subId"] != null)
                //{
                //    string getuserallpromotion = "SELECT IsAllPromotion FROM UserSession WHERE UsID = '" + Session["subId"] + "'";
                //    SqlDbHelper sdh = new SqlDbHelper();
                //    string isall = sdh.ExecuteScalar(getuserallpromotion).ToString();
                //    GetTreelist(Session["usNick"].ToString());
                //    this.username.Text = Session["subNick"].ToString();
                //    if (isall.Equals("1"))
                //    {
                //        this.notuse.Visible = true;
                //        this.goodlist.Visible = false;
                //        this.AspNetPager.Visible = false;
                //    }
                //    else
                //    {
                //        Getgoodlist(null);
                //        //this.username.Text = Session["usNick"].ToString();
                //    }
                //}
                //else
                //{
                //    Getgoodlist(null);
                //    GetTreelist(Session["usNick"].ToString());
                //    this.username.Text = Session["usNick"].ToString();
                //}   
                //Getgoodlist(null);
                GetTreelist(Session["usNick"].ToString());
                this.username.Text = Session["usNick"].ToString();
            }
            ScriptManager.RegisterStartupScript(this, this.GetType(), "resizeImg", "<script>resizeImg()</script>", false);
            ScriptManager.RegisterStartupScript(this, this.GetType(), "onloadfun", "<script>onloadfun();</script>", false);
        }

        /// <summary>
        /// 获取当前会话用户所有活动列表
        /// </summary>
        /// <param name="usNick">当前会话用户昵称</param>
        /// <returns></returns>
        private void GetTreelist(string usNick)
        {
            SqlDbHelper sdh = new SqlDbHelper();
            string getPA = "SELECT * FROM Promotionactive WHERE Owners = '"+ Session["usNick"] +"'";
            DataTable dt = sdh.ExecuteDataTable(getPA);
            TreeNode mtn = new TreeNode("所有活动", "all");
            this.cateTree.Nodes.Add(mtn);
            foreach (DataRow item in dt.Rows)
            {
                TreeNode tn = new TreeNode(item["PromotionactiveName"].ToString(), item["PromotionactiveID"].ToString());
                mtn.ChildNodes.Add(tn);
            }
        }

        protected void cateTree_SelectedNodeChanged(object sender, EventArgs e)
        {
            if (this.cateTree.SelectedValue == "all")
            {
                this.promotionactiveid.Value = "";
                this.promotiondelete.Visible = false;
                return;
            }
            this.promotiontips.Visible = false;
            this.Promotionactives.Visible = true;
            this.promotiondelete.Visible = true;
            this.promotionactiveid.Value = this.cateTree.SelectedValue;
            Getgoodlist(this.cateTree.SelectedValue);
            this.AspNetPager.CurrentPageIndex = 1;
            //ViewState.Clear();

            //if (this.cateTree.SelectedValue == "all")
            //{
            //    Getgoodlist(null);
            //}
            //else
            //{
            //    Getgoodlist(this.cateTree.SelectedValue);
            //}
            //this.AspNetPager.CurrentPageIndex = 1;
            //ScriptManager.RegisterStartupScript(this, this.GetType(), "resizeImg", "<script>resizeImg()</script>", false);
            //ScriptManager.RegisterStartupScript(this, this.GetType(), "onloadfun", "<script>onloadfun();</script>", false);
            ////ScriptManager.RegisterStartupScript(this, this.GetType(), "opendialog", "<script>opendialog();</script>", false);
        }

        protected void closewindow_Click(object sender, EventArgs e)
        {
            Session.Clear();
            Response.Redirect("logout.htm");
        }

        protected void AspNetPager_PageChanging(object src, Wuqi.Webdiyer.PageChangingEventArgs e)
        {

            Getgoodlist(this.cateTree.SelectedValue,e.NewPageIndex);
            //if (ViewState["searchkeyword"] != null)
            //{
            //    bindsearch(e.NewPageIndex);
            //}
            //else
            //{
            //    //GetTradelist(this.AspNetPager.CurrentPageIndex);
            //    Getgoodlist(this.cateTree.SelectedValue == "all" ? null : this.cateTree.SelectedValue, e.NewPageIndex);
            //}
            //ScriptManager.RegisterStartupScript(this, this.GetType(), "resizeImg", "<script>resizeImg()</script>", false);
            //ScriptManager.RegisterStartupScript(this, this.GetType(), "onloadfun", "<script>onloadfun();</script>", false);
            //ScriptManager.RegisterStartupScript(this, this.GetType(), "opendialog", "<script>opendialog();</script>", false);
        }

        //private void bindsearch(long pageno = 1)
        //{
        //    ItemsGetRequest itemsreq = new ItemsGetRequest();
        //    itemsreq.Fields = "num_iid,title,price,pic_url";
        //    itemsreq.Q = ViewState["searchkeyword"].ToString();
        //    itemsreq.PageSize = this.AspNetPager.PageSize;
        //    itemsreq.Nicks = Session["usNick"].ToString();
        //    itemsreq.PageNo = pageno;
        //    ItemsGetResponse itemsrep = client.Execute(itemsreq);
        //    this.goodlist.DataSource = itemsrep.Items;
        //    this.goodlist.DataBind();
        //    this.AspNetPager.RecordCount = int.Parse(itemsrep.TotalResults.ToString());
        //}

        private void Getgoodlist(string cid, int pageno = 1)
        {
            SqlDbHelper sdh = new SqlDbHelper();
            if (cid == null)
            {
                return;
            }
            else
            {
                SqlParameter[] sps = {
                                     new SqlParameter("@tablename","Promotion"), 
                                     new SqlParameter("@pagerow",this.AspNetPager.PageSize), 
                                     new SqlParameter("@pagenow",pageno), 
                                     new SqlParameter("@ordercol","Numid"),
                                     new SqlParameter("@where"," WHERE ParentID = '"+ cid +"'")
                                 };
                DataTable dt = sdh.ExecuteDataTable("sp_page", CommandType.StoredProcedure, null, sps);
                string getrecordcount = "SELECT COUNT(*) FROM Promotion WHERE ParentID = '"+ cid +"'";
                this.AspNetPager.RecordCount = int.Parse(sdh.ExecuteScalar(getrecordcount).ToString());
                this.goodlist.DataSource = dt;
                this.goodlist.DataBind();
            }
            //string getgoodsql = "SELECT * FROM Promotion WHERE ParentID = '"+ cid +"'";
            //DataTable dt = sdh.ExecuteDataTable(getgoodsql);
            //this.AspNetPager.PageSize = dt.Rows.Count;

            //ItemsOnsaleGetRequest onsellreq = new ItemsOnsaleGetRequest();
            //onsellreq.Fields = "num_iid,title,price,pic_url";
            //onsellreq.PageSize = this.AspNetPager.PageSize;
            //onsellreq.PageNo = pageno;
            //if (cid != null)
            //{
            //    onsellreq.SellerCids = cid;
            //}
            //ItemsOnsaleGetResponse onSellRes = client.Execute(onsellreq, Session["sessionKey"].ToString());
            //this.goodlist.DataSource = onSellRes.Items;
            //this.goodlist.DataBind();
            //this.AspNetPager.RecordCount = int.Parse(onSellRes.TotalResults.ToString());
        }

        //protected void search_Click(object sender, EventArgs e)
        //{
        //    if (this.cateTree.SelectedNode != null)
        //    {
        //        this.cateTree.SelectedNode.Selected = false;
        //    }
        //    ViewState.Add("searchkeyword", this.keyword.Text.Trim());
        //    bindsearch();
        //    this.AspNetPager.CurrentPageIndex = 1;
        //    ScriptManager.RegisterStartupScript(this, this.GetType(), "resizeImg", "<script>resizeImg()</script>", false);
        //    ScriptManager.RegisterStartupScript(this, this.GetType(), "onloadfun", "<script>onloadfun();</script>", false);
        //}

        protected void goodlist_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {

                //MarketingPromotionsGetRequest promotionget = new MarketingPromotionsGetRequest();
                //promotionget.Fields = "promotion_id,start_date,end_date,status,tag_id,discount_value,discount_type";
                //promotionget.NumIid = (e.Item.DataItem as Item).NumIid.ToString();
                //promotionget.Status = "ACTIVE";
                //promotionget.TagId = 1;
                //MarketingPromotionsGetResponse promotionresp = client.Execute(promotionget, Session["sessionKey"].ToString());
                //if (!promotionresp.IsError)
                //{
                //    if (promotionresp.Promotions.Count > 0)
                //    {
                //        Promotion p = promotionresp.Promotions.OrderByDescending(pro => pro.EndDate).First();
                //        Panel ap = e.Item.FindControl("activepanel") as Panel;
                //        Panel up = e.Item.FindControl("unactivepanel") as Panel;
                //        ap.CssClass = "hidden";
                //        up.CssClass = "showpanel";
                //        Label pricel = e.Item.FindControl("pricelabel") as Label;
                //        if (p.DiscountType == "PRICE")
                //        {
                //            pricel.Text = "￥"+p.DiscountValue+"元";
                //        }
                //        else
                //        {
                //            pricel.Text = p.DiscountValue + "折";
                //        }
                        
                //        Label startlab = e.Item.FindControl("startlabel") as Label;
                //        Label endlab = e.Item.FindControl("endlabel") as Label;
                //        startlab.Text = p.StartDate.Replace("00:00:00","");
                //        endlab.Text = p.EndDate.Replace("00:00:00", "");
                        
                //    }
                //}
            }
        }

        protected void cateTree_TreeNodeCheckChanged(object sender, TreeNodeEventArgs e)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "resizeImg", "<script>resizeImg()</script>", false);
            ScriptManager.RegisterStartupScript(this, this.GetType(), "onloadfun", "<script>onloadfun();</script>", false);
        }

        protected void createpromotion_Click(object sender, EventArgs e)
        {
            this.cateTree.SelectedNode.Selected = false;
            this.promotiontips.Visible = true;
            this.Promotionactives.Visible = false;
            this.promotiondelete.Visible = false;
            this.promotionactiveid.Value = "";
        }

        protected void reload_Click(object sender, EventArgs e)
        {
            this.cateTree.Nodes.Clear();
            GetTreelist(Session["usNick"].ToString());
            this.cateTree.ExpandAll();
            this.promotiontips.Visible = true;
            this.Promotionactives.Visible = false;
        }
    }
}